# -*- coding: utf-8 -*-
"""
@Time： 2023/12/20 16:20
@Auth： gubei
@File：views.py
@IDE：PyCharm
@Description：
"""

from fastapi import APIRouter, Query, Depends
from sqlalchemy import func
from sqlalchemy.orm import Session
from tortoise.transactions import in_transaction

from api.role.serializers import RoleCreateSchema, RoleUpdateSchema
from core.db.database import get_db
from core.models.models import Role, Permission
from utils.response import *

router = APIRouter()


@router.get("/list", summary='获取角色列表')
async def get_roles(page: int = Query(1, alias="page"), pagesize: int = Query(10), db: Session = Depends(get_db)):
    roles = db.query(Role).filter().offset(page - 1).limit(pagesize).all()
    total_roles = db.query(func.count(Role.id)).scalar()
    # return R.suc(data=roles, total=total_roles)
    return R.paginate(data=roles, total=total_roles, page=page, page_size=pagesize)



@router.post('/role', summary='添加角色并赋予权限')
async def add_role(roleCreate: RoleCreateSchema, db: Session = Depends(get_db)):
    """添加角色并赋予权限"""

    role = db.query(Role).filter_by(name=roleCreate.name).first()

    if not role:
        role = Role(name=roleCreate.name)
        db.add(role)
        db.commit()

        new_role = db.query(Role).filter_by(name=roleCreate.name).first()

        permissions = Permission(content=str(roleCreate.permissions), role_id=new_role.id)
        permissions.save()

        return R.suc()
    else:
        return R.suc(msg="角色已经存在")


@router.put('/role', summary='修改角色权限')
async def update_role(roleUpdateSchema: RoleUpdateSchema, db: Session = Depends(get_db)):
    """修改权限"""

    role = db.query(Role).filter_by(id=roleUpdateSchema.id).first()
    if not role:
        return R.err(msg='角色不存在')

    role.name = roleUpdateSchema.name
    role.Permissions[0].content = str(roleUpdateSchema.permissions)
    db.commit()

    return R.suc()


@router.delete("/{role_id}", summary='删除角色信息')
async def delete_role(role_id: int, db: Session = Depends(get_db)):
    role = db.query(Role).filter(Role.id == role_id).first()
    role.is_delete = 1
    role.Permissions[0].is_delete = 1
    db.commit()
    return R.suc(msg="角色删除成功")
